/**
 * 全局 GA4 埋点方法
 * 支持:
 *  - 自动检查 gtag 是否存在
 *  - 自动补充 page_path / page_title / page_location
 *  - 自定义事件参数
 *  - Typescript 提示
 */

import { useUserStore } from '@/store/user';

export interface GAEventParams {
  label?: string;
  category?: string;
  value?: number;
  [key: string]: any;
}

// 获取用户ID
function getUserId() {
  const userStore = useUserStore();
  return userStore.user?.uid || '';
}

export function sendGAEvent(eventName: string, params: GAEventParams = {}) {
  if (typeof window === 'undefined') return;

  const gtag = (window as any).gtag;
  if (typeof gtag !== 'function') {
    console.warn('[GA] gtag not ready');
    return;
  }

  const autoParams = {
    userId: getUserId(),
    ...params,
  };

  console.log('GA参数:', autoParams);

  try {
    gtag('event', eventName, autoParams);
  } catch (e) {
    console.warn('[GA] event error:', e);
  }
}
